package com.itany.shop.factory;

import com.itany.shop.exception.ObjectNotFoundException;
import com.itany.shop.util.ParameterUtil;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 石小俊
 */
public class ObjectFactory {

    private static Map<String, Object> objs;


    static {
        objs = new HashMap<>();
        BufferedReader br = null;
        try {
            br = new BufferedReader(
                    new InputStreamReader(
                            ObjectFactory
                                    .class
                                    .getClassLoader()
                                    .getResourceAsStream("beans.properties")));
            String line = null;
            while ((line = br.readLine()) != null) {
                // 当读取到的行中数据不为空,则进行处理
                if (!ParameterUtil.isNull(line)) {
                    // 如果以#开头表示注释,不做处理
                    if (line.startsWith("#")) {
                        continue;
                    }
                    // 取出这一行数据,根据等号分割
                    String[] arr = line.split("=");
                    String key = arr[0];
                    String value = arr[1];
                    // 根据value所表示的包名.类名获取对应的Class类型
                    Class c = Class.forName(value);
                    // 调用无参构造方法创建对应的对象
                    Object obj = c.newInstance();
                    // 将key与obj存储到Map集合中
                    objs.put(key, obj);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new ExceptionInInitializerError("ObjectFactory初始化失败");
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    throw new ExceptionInInitializerError("释放资源出错");
                }
            }
        }
    }

    public static Object getObject(String key) {
        Object obj = objs.get(key);
        if (null == obj) {
            throw new ObjectNotFoundException("根据指定的key:" + key + "在配置文件中没有找到对应的配置");
        }
        return obj;
    }

}
